<?php
namespace Home\Controller;
use Think\Controller;

// require_once 'qiniusdk/autoload.php';    
Vendor('Qiniusdk.autoload');  //七牛入口文件引入  
use Qiniu\Auth;  
use Qiniu\Storage\UploadManager;          
use Qiniu\Storage\BucketManager;  
/**
* 消息相关控制器
*/
class NewsController extends Controller{
	public function index(){
		$this->dislay();
	}

	/**
	* 我的消息列表
	*/
	public function message1(){

		$user_id = get_user();
		$page_no = I('post.page_no') ? I('post.page_no') : 1;

		if ($page_no ==1) 
		{
			$data1 = M('message')->where('type=0 AND shou_id='.$user_id)
			->field('id,fa_id,shou_id,content,add_time,status,type')
			->group('fa_id')
			->order('id desc')
			->select();

			foreach ($data1 as $key => $value) {
				$data1[$key]['num'] = M('message')->where('type=0 AND status=0 AND shou_id='.$user_id)->count();
				$data1[$key]['photo_id'] = __ROOT__.C('XI_IMAGE');
				$data1[$key]['username'] = '系统助手';
				$data1[$key]['content'] = M('message')->where('type=0 AND shou_id='.$user_id)->order('id desc')->getField('content');
			}
		}

		$data2 = M('message a')
			->page($page_no,10)
			->where('a.type!=0')
			->where("(a.shou_id=$user_id)")
			->group('a.fa_id')
			->field('a.id,a.fa_id,a.shou_id,a.content,a.add_time,a.status,a.type,b.photo_id,b.username')
			->join('left join zm_user b on a.fa_id=b.id')
			->select();
		foreach ($data2 as $key => $value) {
			$data2[$key]['num'] = M('message')->where("status=0 AND shou_id=$user_id AND fa_id=".$value['fa_id'])->count();
			if ($value['shou_id']==$user_id) {
				$data2[$key]['content'] = M('message')->where(array('shou_id'=>$user_id,'fa_id'=>$value['fa_id']))->order('id desc')->getField('content');
			}
			
		}
	
		$data = array_merge($data1,$data2);
		
		foreach ($data as $key => $value) {
			$data[$key]['add_time'] = date('Y-m-d H:i:s' ,$value['add_time']);
		}
		// dump($data);exit();
		if ($data) 
		{	
			$result["result"]  = true;
			$result['message'] = "查询成功";
			$result['list'] = $data;
			$this->ajaxReturn($result);
		}else
		{	
			$result["result"]  = false;
			$result['message'] = "没有数据";
			$result['list'] = '';
			$this->ajaxReturn($result);
		}
	}

	/**
	* 我的消息列表
	*/
	public function message(){
		$user_id = get_user();
		$page_no = I('post.page_no') ? I('post.page_no') : 1;

		if ($page_no ==1) 
		{	
			$system = M('config_img')->where('id=5 OR id=6')->select();
			$data1 = M('message_list')
				// ->where('shou_id=0')
				->where("(fa_id=0 AND shou_id=$user_id) OR (fa_id=$user_id AND shou_id=0)")
				->limit(1)
				->select();
			// dump($data1);exit();
			foreach ($data1 as $key => $v) {
				$list1[$key]['num'] = M('message')->where('type=0 AND status=0 AND fa_id=0 AND shou_id='.$user_id)->count();
				$list1[$key]['photo_id'] = __ROOT__.$system[0]['image']; //__ROOT__.C('XI_IMAGE');
			
				$list1[$key]['username'] = $system[0]['val'];//'系统助手';
			
				$list1[$key]['content'] = $v['news'];
				$list1[$key]['mess_id'] = $v['id'];
				$list1[$key]['add_time']= $v['add_time'];
				$list1[$key]['fa_id']= '0';
				$list1[$key]['shou_id']= $user_id;
			}
			$data3 = M('message_list')
				// ->where('shou_id=0')
				->where("(fa_id=3 AND shou_id=$user_id) OR (fa_id=$user_id AND shou_id=3)")
				->limit(1)
				->find();
			for ($i=0; $i < 1; $i++) { 
				$list3[$i]['num'] = M('message')->where('status=0 AND fa_id=3 AND shou_id='.$user_id)->count();
				$list3[$i]['photo_id'] = __ROOT__.$system[1]['image'];//__ROOT__.C('MM_IMAGE');
				$list3[$i]['username'] = $system[1]['val'];//'客服MM';
				$list3[$i]['content'] = $data3['news'] ? $data3['news'] : '';
				$list3[$i]['mess_id'] = $data3['id'];
				$list3[$i]['add_time']= $data3['add_time'] ? $data3['add_time'] : time();
				$list3[$i]['fa_id']= '3';
				$list3[$i]['shou_id']= $user_id;
			}
			// dump($list3);exit();
		}

		if (!$data1) {
			$list1 =array();
			$list3 =array();
		}

		$data2 = M('message_list')
			->where(array('fa_id'=>$user_id,'shou_id'=>array('neq',3)))
			// ->where("(fa_id=$user_id AND shou_id>0) OR (shou_id=$user_id AND fa_id>0)")
			->page($page_no,10)
			->order('add_time desc')
			->select();
		// dump($data2);exit();
		foreach ($data2 as $key => $v) {
			if ($v['fa_id']==$user_id) 
			{
				$user[$key] = M('user')->where(array('id'=>$v['shou_id']))->field('id,photo_id,username')->find();
				$ids = $user[$key]['id'];
			}else
			{
				$user[$key] = M('user')->where('id='.$v['fa_id'])->field('id,photo_id,username')->find();
				$ids = $user[$key]['id'];
			}
			// dump($ids);exit();"status=0 AND shou_id=$user_id AND fa_id=$ids"
			$list2[$key]['num'] = M('message')->where(array('status'=>0,'shou_id'=>$user_id,'fa_id'=>$ids))->count();
			$list2[$key]['photo_id'] = $user[$key]['photo_id'];
			$list2[$key]['username'] = $user[$key]['username'];
			$list2[$key]['content'] = $v['news'];
			$list2[$key]['mess_id'] = $v['id'];
			$list2[$key]['add_time']= $v['add_time'];
			$list2[$key]['fa_id'] = $user[$key]['id'];
			$list2[$key]['shou_id']= $user_id;
		}
		// dump($data2);exit();
		if (!$data2) {
			$list2 =array(); 
		}

		$data = array_merge($list1,$list3,$list2);
		
		foreach ($data as $key => $value) {
			$data[$key]['add_time'] = date('Y-m-d H:i:s' ,$value['add_time']);
		}
		// dump($data);exit();
		if ($data) 
		{	
			$result["result"]  = true;
			$result['message'] = "查询成功";
			$result['list'] = $data;
			$this->ajaxReturn($result);
		}else
		{	
			$result["result"]  = false;
			$result['message'] = "没有数据";
			$result['list'] = '';
			$this->ajaxReturn($result);
		}

	}

	/**
	* 我的消息
	*/
	public function info(){

		$user_id = get_user();
		$shou_id = I('post.fa_id') ? I('post.fa_id') : 0;//发送给我的人的id 对于我来说就是shouid
		$page_no = I('post.page_no') ? I('post.page_no') : 1;
		// $myfile=fopen("log.txt", "w");fwrite($myfile, $shou_id);
		if ($shou_id<0) {
			$this->ajaxReturn(is_not('fa_id必须'));
		}
		if($user_id > $shou_id){
			$map['max_del'] = 0;
		}else{
			$map['min_del'] = 0;
		}

		/*if($shou_id != 0){
			$map['status'] = 1;
		}
		*/
		$data = M('message')
			->page($page_no,20)
			->where("(fa_id=$shou_id AND shou_id=$user_id) OR (fa_id=$user_id AND shou_id=$shou_id)")
			->where($map)
			->order('id desc')
			->field('id,fa_id,shou_id,content,add_time,status,type,url,interval')
			->select();
		$interval = 0;
		$last_time = $data ? $data[0]['add_time'] : 0;
		$dataLen = count($data);
		$datalist = array();
		for($i = 0 ; $i<$dataLen ; $i++){
			$datalist[$i] = $data[$dataLen - $i -1];
		}
		foreach ($datalist as $key => $value) {
			if($value['interval'] > $interval){
				$interval = $value['interval'];
				$datalist[$key]['add_time'] = date('Y-m-d H:i:s' ,$value['add_time']);
			}else{
				$datalist[$key]['add_time'] = '';
			}
			if ($value['fa_id'] == $user_id) {
				$datalist[$key]['is_zuoyou'] = 'wo';
			}else{
				$datalist[$key]['is_zuoyou'] = 'ta';
			}
		}
		$list['wo'] = M('user')->where('id='.$user_id)->field('username as wo_name,photo_id as wo_photo_id')->find();
		
		$list['ta'] = M('user')->where('id='.$shou_id)->field('username as ta_name,photo_id as ta_photo_id')->find();

		if ($shou_id ==0) {
			$list['ta'] = array('wo_name'=>'系统助手','ta_photo_id'=> __ROOT__.C('XI_IMAGE'));
		}
		$is_friend = 0;
		if($user_id == 3 || $shou_id == 3 || $shou_id == 0 || $user_id == 0){
			$is_friend = 1;
		}else{
			$is_friend1 = M('follow')->where("user_id=$user_id AND fo_user_id=$shou_id")->getField('is_friend');
			$is_friend2 = M('follow')->where("user_id=$shou_id AND fo_user_id=$user_id")->getField('is_friend');
			if($is_friend1==1 && $is_friend2==1){
				$is_friend = 1;
			}
		}
		
		M('message')
			->where("fa_id=$shou_id AND shou_id=$user_id")
			->save(array('status'=>1));
		if ($data) 
		{	
			$result["result"]  = true;
			$result['message'] = "查询成功";
			$result['image'] = $list;
			$result['list'] = $datalist;
			$result['is_friend'] = $is_friend;
			$result['shou_id'] = $user_id;
			$result['last_time'] = $last_time;
			$this->ajaxReturn($result);
		}else
		{	
			$result["result"]  = false;
			$result['message'] = "没有数据";
			$result['list'] = '';
			$result['is_friend'] = $is_friend;
			$this->ajaxReturn($result);
		}
	}

	/**
	* 我的消息
	*/
	public function info1(){

		$user_id = get_user();
		$mess_id = I('post.mess_id') ? I('post.mess_id') : 0;
		$page_no = I('post.page_no') ? I('post.page_no') : 1;
		// $myfile=fopen("log.txt", "w");fwrite($myfile, $shou_id);
		if ($page_no<0) {
			$this->ajaxReturn(is_not('fa_id必须'));
		}
		$data = M('message')
			->page($page_no,20)
			->where("mess_id=".$media_id)
			->field('id,fa_id,shou_id,content,add_time,status,type,url,interval')
			->select();
		$interval = 0;
		foreach ($data as $key => $value) {
			if($value['interval'] != $interval){
				$interval = $value['interval'];
				$data[$key]['add_time'] = date('Y-m-d H:i:s' ,$value['add_time']);
			}else{
				$data[$key]['add_time'] = '';
			}
			
			if ($value['fa_id'] == $user_id) {
				$data[$key]['is_zuoyou'] = 'wo';
			}else{
				$data[$key]['is_zuoyou'] = 'ta';
			}
		}
		$list['wo'] = M('user')->where('id='.$user_id)->field('username as wo_name,photo_id as wo_photo_id')->find();
		
		$list['ta'] = M('user')->where('id='.$shou_id)->field('username as ta_name,photo_id as ta_photo_id')->find();

		if ($shou_id ==0) {
			$list['ta'] = array('wo_name'=>'系统助手','ta_photo_id'=> __ROOT__.C('XI_IMAGE'));
		}
		M('message')
			->where("fa_id=$shou_id AND shou_id=$user_id")
			->save(array('status'=>1));
		if ($data) 
		{	
			$result["result"]  = true;
			$result['message'] = "查询成功";
			$result['image'] = $list;
			$result['list'] = $data;
			$result['shou_id'] = $user_id;
			// dump($result);exit();
			$this->ajaxReturn($result);
		}else
		{	
			$result["result"]  = false;
			$result['message'] = "没有数据";
			$result['list'] = '';
			$this->ajaxReturn($result);
		}
	}

	/**
	* 消息发送
	*/
	public function sendMessage(){
		$user_id = get_user();
		$shou_id = I('post.shou_id') ? I('post.shou_id') : $this->ajaxReturn(is_not('shou_id'));
		$content = I('post.content') ? I('post.content') : $this->ajaxReturn(is_not('content'));

		$now = time();
		$sendTime = $now;
		if(!session('msgIntv')){
			$me = M('message')->where("(fa_id=$user_id AND shou_id=$shou_id) OR (fa_id=$shou_id AND shou_id=$user_id)")
			                  ->order('id desc')->getField('interval');
			$me = $me ? $me : 1;
			$he = M('message')->where(array('fa_id'=>$shou_id,'shou_id'=>$user_id))
							    ->order('id desc')->getField('interval');
			$he = $he ? $he : 1;
			$the_max = max($me,$he);
			if(($now - $the_max*5*60) > 5*60){
				session('msgIntv',array('intv'=>$now,'last'=>$now));
			}else{
				session('msgIntv',array('intv'=>($the_max+1)*5*60,'last'=>$now));
			}
		}else{
			if(($now - session('msgIntv.last')) > 5*60){
				session('msgIntv',array('intv'=>$now,'last'=>$now));
			}else{
				$sendTime = 0;
				session('msgIntv',array('intv'=>session('msgIntv.intv'),'last'=>$now));
			}
		}
		$interval = intval(session('msgIntv.intv')/(5*60));

		$mess = M('message_list')
			// ->where("(fa_id=$shou_id AND shou_id=$user_id) OR (fa_id=$user_id AND shou_id=$shou_id)")
			->where("(fa_id=$user_id AND shou_id=$shou_id)")
			->find();
		if (!$mess) 
		{
			$mess['id']=M('message_list')->add(array('fa_id'=>$user_id,'shou_id'=>$shou_id,'news'=>$content,'add_time'=>$now));
		}else
		{
			M('message_list')->where('id='.$mess['id'])->save(array('news'=>$content,'add_time'=>$now));
		}
		$mess1 = M('message_list')
			->where("(fa_id=$shou_id AND shou_id=$user_id)")
			->find();
		if (!$mess1)
		{
			$mess1['id']=M('message_list')->add(array('fa_id'=>$shou_id,'shou_id'=>$user_id,'news'=>$content,'add_time'=>$now));
		}else
		{
			M('message_list')->where('id='.$mess1['id'])->save(array('news'=>$content,'add_time'=>$now));
		} 

		$list=array(
			'add_time'=>$now,
			'fa_id'   =>$user_id,
			'shou_id' =>$shou_id,
			// 'content' =>urldecode($content),
			'content' =>$content,//$content,
			'type'    =>2,
			'status'  =>0,
			'mess_id' =>$mess['id'], 
			'interval'=>$interval
		);
		
		$data = M('message')->add($list);

		$wxopanid = M('user')->where(array('id'=>$shou_id))->getField('openid');
		$status = get_rong_status($shou_id);
		if ($status ==0) 
		{	
			if (C('NEWS_CONFIG') == '1') 
			{
				$num = M('message')->where(array('shou_id'=>$shou_id,'status'=>0))->count();
				$content = "您有".$num."条消息未读";
			}else{
				$content = $content;
			}
			A('Index')->wx_message($wxopanid,urldecode($content));
		}
		if ($data) 
		{	
			$result["result"]  = true;
			$result['message'] = "发送成功";
			$result['message_id'] = $data;
			$result['is_time'] = $sendTime;
			$this->ajaxReturn($result);
		}else
		{
			$this->ajaxReturn(is_not('发送失败'));
		}
		
	}

	/**
	* 消息删除
	*/
	public function delMessage(){
		$user_id = get_user();
		$fa_id = I('post.fa_id') ? I('post.fa_id') : $this->ajaxReturn(is_not('fa_id'));

		$map['fa_id'] = $user_id;
		$map['shou_id'] = array('in' , $fa_id);

		$is = in_array(3, $fa_id) ? $this->ajaxReturn(is_not('客服号不能删除')) : 0;
		// $data = M('message')->where($map)->save();
		$fa_array = explode(",",$fa_id);
		foreach ($fa_array as $key => $value) {
			//如果我的id比对方的要大 我就是max_del
			if($user_id > $value){
				M('message')->where("(fa_id=$user_id AND shou_id=$value) OR (fa_id=$value AND shou_id=$user_id)")->save(array('max_del'=>1));
			}else{
				M('message')->where("(fa_id=$user_id AND shou_id=$value) OR (fa_id=$value AND shou_id=$user_id)")->save(array('min_del'=>1));
			}
		}

		$data = M('message_list')->where($map)->delete();
			
		if ($data) 
		{	
			$result["result"]  = true;
			$result['message'] = "删除成功";
			$result['list'] = $data;
			$this->ajaxReturn($result);
		}else
		{	
			$result["result"]  = false;
			$result['message'] = "删除失败";
			$this->ajaxReturn($result);
		}
	}

	/**
	* 在线聊天消息已读
	*/
	public function NotReadToRead(){
		$msg_id = I('post.msg_id');
		$res = M('message')->where('id='.$msg_id)->save(array('status'=>1));
		if($res === false)
		{
			$this->ajaxReturn(array('status'=>0,'message'=>'操作失败'));
		}
		$this->ajaxReturn(array('status'=>1,'message'=>'操作成功'));
	}

	/**
	* 语音下载 微信下载过来
	*/
	public function sendVoice(){
		$user_id = get_user();
		$media_id=I('get.media_id');
		// $data = M('user')->where('id='.$user_id)->save(array('voice_id'=>$media_id));
		
		// $media_id='qLdAR6Jd7nKDQZXLCMoSh-_CDQaOQLqeVa3GY2E73vxJESpfGn_g7QH9LYklhl62';
		$token = A('Index')->gettoken();
		// $token = 'Js9QWSlCkYAJmF6cy-a-OnvCLzCcU1WH9Pcf82BG8tnlY6HT2nwm7LhPDQN8VggWu_CbshKvgtOLnSimXnZJzVaU-0IcoDR2Ej6FZsHq3IzGGRscxu7Q9dZ_kbJ2bXQvZJIjAEAPZY';
		// dump($token);
		$url='http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$token.'&media_id='.$media_id;

        $ch = curl_init($url);  
        curl_setopt($ch, CURLOPT_HEADER, 0);  
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头  
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
        $package = curl_exec($ch);  
        $httpinfo = curl_getinfo($ch);  
        curl_close($ch);  
          
        $prefix=explode("/", $httpinfo["content_type"]);  
          
        $filename=time().".".$prefix[1];
        // dump($filename);
        //$this->saveWeixinFile($filename, $package);  
        $local_file = fopen("Public/Uploads/active/".$filename, 'w'); 
        $state=fwrite($local_file, $package);  
        fclose($local_file);
        $voice_id = "Public/Uploads/active/".$filename;
        $data=$this -> upchange($voice_id);
        if ($data) 
        {   
            $result["result"] = true;
            $result['message'] = "成功";
            $result['media_id'] = $data['url'];
            $this->ajaxReturn($result);
        }else
        {
            $result["result"] = false;
            $result["message"] = '失败';
            $this->ajaxReturn($result);
        }
	}


	public function upchange($vid=''){ 
		$user_id = get_user();   
        //$filePath,$mediaid
        $mediaid = 'voice_'.$user_id.time();
        // $filePath ="Public/Uploads/active/1491726273.amr";
        // $file = fopen($filePath, 'rb');
        // unlink($filePath);
        // dump($file);exit();
        $filePath = $vid;
	    $accessKey = trim(C('qiliu_ak'));      //七牛公钥    
	    $secretKey = trim(C('qiliu_sk'));      //七牛私钥    
	    $auth = new Auth($accessKey, $secretKey);    
	           
	    $bucket = trim('nextvoice');    
	    //数据处理队列名称,不设置代表不使用私有队列，使用公有队列。    
	    $pipeline = trim($reply['pipeline']);    
	            
	    //通过添加'|saveas'参数，指定处理后的文件保存的bucket和key    
	    //不指定默认保存在当前空间，bucket为目标空间，后一个参数为转码之后文件名     
	    $savekey = \Qiniu\base64_urlSafeEncode($bucket.':'.$mediaid.'.mp3');   
	    //设置转码参数    
	    $fops = "avthumb/mp3/ab/320k/ar/44100/acodec/libmp3lame";    
	    $fops = $fops.'|saveas/'.$savekey;    
	    if(!empty($pipeline)){  //使用私有队列    
	        $policy = array(    
	            'persistentOps' => $fops,    
	            'persistentPipeline' => $pipeline
	        );    
	    }else{                  //使用公有队列    
	        $policy = array(    
	            'persistentOps' => $fops    
	        );    
	    }    
	            
	    //指定上传转码命令    
	    $uptoken = $auth->uploadToken($bucket, null, 3600, $policy);    
	    $key = $mediaid.'.amr'; //七牛云中保存的amr文件名    
	    $uploadMgr = new UploadManager();    
	            
	    //上传文件并转码$filePath为本地文件路径    
	    list($ret, $err) = $uploadMgr->putFile($uptoken, $key, $filePath);
	    // dump($ret);exit();
	    if ($err !== null) {    
	        return false;    
	    }else {    
	        //此时七牛云中同一段音频文件有amr和MP3两个格式的两个文件同时存在    
	        $bucketMgr = new BucketManager($auth);
	        //为节省空间,删除amr格式文件    
	        $bucketMgr->delete($bucket, $key);
	        $urls = "http://oo4scjof9.bkt.clouddn.com/".$mediaid.'.mp3';
	        $data = M('user')->where(array('id'=>$user_id))->save(array('voice_id'=>$urls,'voice_status'=>0));
	        unlink($filePath);
	        $result["result"] = true;
            $result['url'] = $urls;
	        return $result;
	        return $ret['key'];
	    }    
	}  
}